package com.hspedu.seckill.config;

import com.hspedu.seckill.entity.User;
import com.hspedu.seckill.model.context.UserContext;
import com.hspedu.seckill.service.UserService;
import com.hspedu.seckill.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: xujiabing
 * @date: 2024-10-04 15:35
 * @description 自定义参数解析器
 */
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private UserService userService;

    //所有请求都会放行
    //判断当前 解析的参数类型 是不是所需要的
    //如果这个方法返回true 才会执行下面的resolveArgument 方法
    //返回false 不执行下面的方法
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //获取参数是不是user 类型
        Class<?> aClass = parameter.getParameterType();
        //如果为true, 就执行resolveArgument
        return aClass == User.class;
    }

    //个方法，类似拦截器，将传入的参数，取出cookie 值，然后获取对应的User 对象并把这个User 对象作为参数继续传递.
    @Override
    public Object resolveArgument(MethodParameter parameter,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) throws Exception {

//        HttpServletRequest request = webRequest
//                .getNativeRequest(HttpServletRequest.class);
//        HttpServletResponse response = webRequest
//                .getNativeResponse(HttpServletResponse.class);
//
//        String ticket = CookieUtil.getCookieValue(request, "userTicket");
//        if (!StringUtils.hasText(ticket)) {
//            return null;
//        }
//        //根据cookie-ticket 到Redis 获取User
//        return userService.getUserByCookie(ticket, request, response);

        // v2.0 改成由自定义拦截器，获取user放入ThreadLocal中
        return UserContext.getUser();
    }

}
